package org.example.gateway.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.example.gateway.bean.User;
import org.example.gateway.contants.AdminConstants;
import org.example.gateway.enums.GatewayExceptionEnum;
import org.example.gateway.exceptions.GatewayException;
import org.example.gateway.mapper.UserMapper;
import org.example.gateway.pojo.PayLoad;
import org.example.gateway.pojo.UserDto;
import org.example.gateway.service.UserService;
import org.example.gateway.utils.DateTimeUtil;
import org.example.gateway.utils.JwtUtils;
import org.example.gateway.utils.StrUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;

@Service
public class UserServiceImpl implements UserService {
    private final static Logger log = LoggerFactory.getLogger(UserServiceImpl.class);

    @Resource
    private UserMapper userMapper;

    @Value("${gateway.user-password-salt}")
    private String salt;

    @Override
    public void add(UserDto dto) {
        User oldName = queryByName(dto.getUserName());
        if (oldName != null) {
            throw new GatewayException("the userName already exist");
        }
        User user = new User();
        user.setUserName(dto.getUserName());
        user.setPassword(StrUtil.md5Digest(dto.getPassword(), salt));
        user.setCreatedTime(DateTimeUtil.LocalDateTime2Date(LocalDateTime.now()));
        userMapper.insert(user);
    }

    @Override
    public void login(UserDto dto, HttpServletResponse response) {
        User user = queryByName(dto.getUserName());
        if (user == null) {
            throw new GatewayException(GatewayExceptionEnum.LOGIN_ERROR);
        }
        String pwd = StrUtil.md5Digest(dto.getPassword(), salt);
        if (!pwd.equals(user.getPassword())) {
            throw new GatewayException(GatewayExceptionEnum.LOGIN_ERROR);
        }
        PayLoad payLoad = new PayLoad(user.getId(), user.getUserName());
        try {
            String token = JwtUtils.generateToken(payLoad);
            Cookie cookie = new Cookie(AdminConstants.TOKEN_NAME, token);
            cookie.setHttpOnly(true);
            // 30min
            cookie.setMaxAge(30 * 60);
            cookie.setPath("/");
            response.addCookie(cookie);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private User queryByName(String userName) {
        QueryWrapper<User> wrapper = Wrappers.query();
        wrapper.lambda().eq(User::getUserName, userName);
        return userMapper.selectOne(wrapper);
    }
}
